package no.uio.ifi.cop.lex;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * This class tries to match a Tokens based on a regular.
 *
 * Note that tokens should be given without their start
 * end stop meta characters since these are added.
 *
 * @version 1.0
 * @author bjarneh@ifi.uio.no
 */

class TokenMatcher{

    int ordinal;
    String tostring, id;
    Pattern start, entire;

    public TokenMatcher(int ordinal, String regex, String id){
        
        String representation; Matcher m;
        Pattern nlreplace, tabreplace;
        
        // to be able to give a nice presentation of the
        // regular expressions we need to escape a few
        // newline, tab and so on
        nlreplace = Pattern.compile("\n");
        tabreplace = Pattern.compile("\t");
        m = nlreplace.matcher("^"+regex+"$");
        representation = m.replaceAll("\\\\n");
        m = tabreplace.matcher(representation);
        tostring = m.replaceAll("\\\\t");

        this.ordinal = ordinal;
        this.id      = id;
        start = Pattern.compile("^"+regex);
        entire = Pattern.compile("^"+regex+"$");
    }

    protected boolean startMatch(CharSequence s){
        return start.matcher(s).matches();
    }

    protected boolean entireMatch(CharSequence s){
        return entire.matcher(s).matches();
    }

    public String toString(){
        return String.format("TokenMatcher[ %s ]:  %s", id, tostring);
    }

    public int length(){
        return tostring.length();
    }

}
